let request = require("./request");

let Sms = require("./url/sms");

let config = require("./config");

let argv = process.argv.slice(2);
let arg = {};
argv.forEach((item) => {
  let com = item.split("=");
  let key = com[0];
  let val = com[1];
  arg[key] = val;
});

function send() {
  Sms.forEach(async (item) => {
    let params = {};
    let data = item.data;
    for (let key in data) {
      if (config[key]) {
        params[data[key]] = config[key];
      } else {
        params[key] = data[key];
      }
    }
    let pobj = {};
    if (item.methods == "get") {
      let url = item.url;
      for (let key in params) {
        url += `${key}=${params[key]}&`;
      }
      pobj = {
        url: url.slice(0, -1),
        method: item.methods,
      };
    } else {
      pobj = {
        url: item.url,
        method: item.methods,
        data: params,
      };
    }
    request(pobj)
      .then((res) =>
        console.log(
          `\x1B[32m ==${pobj.url}-=${JSON.stringify(res?.data)
            ?.slice(0, 60)
            ?.trim()}==  \x1B[0m`
        )
      )
      .catch((err) =>
        console.log(`\x1B[31m ==${pobj.url}--${err}===  \x1B[0m`)
      );

    await wait(0.1);
  });
}

function wait(time) {
  return new Promise((res) => {
    setTimeout(() => {
      res();
    }, time);
  });
}

async function start() {
  let count = arg?.time ?? 1;
  let sleep = arg?.sleep ?? null;
  console.log(`\x1B[32m ========---任务执行开始---========  \x1B[0m`);
  for (let i = 0; i < count; i++) {
    send();
    if (sleep && i + 1 < count) {
      console.log(`\x1B[34m--第${i + 1}次结束，休息${sleep}s--\x1B[0m`);
      await wait(sleep * 1000);
    }
  }
  console.log(`\x1B[32m ========---任务执行结束---========  \x1B[0m`);
}

start();
